import { NextResponse } from 'next/server'
import prisma from '@/lib/db'
import {verifyToken} from '@/lib/auth'


export async function POST(request: Request): Promise<Response> {
  try {
    const token = request.headers.get('Authorization')?.split(' ')[1]
    const payload = token ? verifyToken(token) : null;
  
    if (!payload) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json()

    const newTopic = await prisma.productTopic.create({
      data: {
        ...body,
        id: crypto.randomUUID(),
      }
    })
    
    return new Response(JSON.stringify(newTopic), {
      status: 201,
      headers: {
        'Content-Type': 'application/json'
      }
    })
  } catch (error: any) {
    return new Response(JSON.stringify({ error: error.message || '创建话题失败' }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    })
  }
}

export async function PUT(request: Request): Promise<Response> {
  try {
    const token = request.headers.get('Authorization')?.split(' ')[1]
    const payload = token ? verifyToken(token) : null;
  
    if (!payload) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json()
    
    
    const updatedTopic = await prisma.productTopic.update({
      where: { id: body.id },
      data: {
        name:body.name
      }
    })
    return new Response(JSON.stringify(updatedTopic), {
      headers: {
        'Content-Type': 'application/json'
      }
    })
  } catch (error: any) {
    return new Response(JSON.stringify({ error: error.message || '更新失败' }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    })
  }
}
